﻿using System.Linq.Expressions;

namespace MySql.Simple.Mapper.Linq.ExpressionVisitors
{
    /// <summary>
    /// Transforms <see cref="NewExpression"/> objects into MySQL syntax
    /// </summary>
    public class MethodCallExpressionVisitor : IExpressionVisitor
    {
        /// <summary>
        /// Determines whether this instance can visit the specified expression.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <returns>
        /// 	<c>true</c> if this instance can visit the specified expression; otherwise, <c>false</c>.
        /// </returns>
        public bool CanVisit(Expression expression)
        {
            return expression is MethodCallExpression;
        }

        /// <summary>
        /// Visits the specified expression and returns a string representation of it's contents.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <param name="query"></param>
        /// <returns></returns>
        public SqlQuery Visit(Expression expression, SqlQuery query)
        {
            var methodCallExpression = (MethodCallExpression)expression;

            if (methodCallExpression.Method.Name != "Where")
            {
                query.Operation += methodCallExpression.Method.Name.ToUpper();
            }

            foreach(var argument in methodCallExpression.Arguments)
            {
                query = new SqlGenerator().Generate(argument, query);
            }

            return query;
        }
    }
}
